package com.clz.hyperit.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.clz.hyperit.entity.Article;
import com.clz.hyperit.entity.Tag;
import com.clz.hyperit.entity.UserDetail;
import com.clz.hyperit.service.ArticleService;
import com.clz.hyperit.service.TagService;
import com.clz.hyperit.service.UserDetailService;
import com.clz.hyperit.util.FileUploadUtil;
import com.clz.hyperit.util.ResultMessage;
import com.clz.hyperit.vo.PageInfo;
import com.clz.hyperit.vo.UserArticle;

@RestController
@RequestMapping(value = "/article")
public class ArticleController {
	private ResultMessage result = null;
	@Autowired
	private ArticleService articleService;

	@Autowired
	private TagService tagService;

	@Autowired
	private UserDetailService userDetailService;

	private final Logger logger = LoggerFactory
			.getLogger(ArticleController.class);

	/**
	 * 分页查询所有博文-时间排序
	 * 
	 * @param rank
	 * @param field
	 * @param pageInfo
	 * @return
	 */
	@RequestMapping(value = "/getArticle", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> getArticle(PageInfo pageInfo,
			Integer status) {
		result = new ResultMessage();
		result.setServiceResult(true);
		List<Article> article_list = articleService.findArticle(pageInfo,
				status);
		if (article_list.size() <= 0) {
			result.setServiceResult(false);
			result.setResultInfo("没有更多了");
		}
		List<UserArticle> list = getUserArticle(article_list);
		result.getResultParm().put("article_user", list);
		result.getResultParm().put("total_count", pageInfo.getTotalCount());
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}

	/**
	 * 分页查询个人的所有博文
	 * 
	 * @param pageInfo
	 * @param status
	 * @param id
	 *            ->userdetail_id
	 * @return
	 */
	@RequestMapping(value = "/getPersonArticle", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> getPersonArticle(Integer id,
			PageInfo pageInfo, Integer status) {
		result = new ResultMessage();
		result.setServiceResult(true);
		List<Article> article_list = articleService.findPersonArticle(id,
				pageInfo, status);
		if (article_list.size() <= 0) {
			result.setServiceResult(false);
			result.setResultInfo("没有更多了");
		}
		UserDetail ud = userDetailService.getUserInfo(id);
		result.getResultParm().put("article_list", article_list);
		result.getResultParm().put("total_count", pageInfo.getTotalCount());
		result.getResultParm().put("userdetail", ud);
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}

	/**
	 * 发表文章/存草稿
	 * 
	 * @param id
	 * @param pageInfo
	 * @param status
	 * @return
	 */
	@RequestMapping(value = "/saveArticle", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> saveArticle(Integer id,
			Article article, Integer status, String tag) {
		result = new ResultMessage();
		result.setServiceResult(true);
		if (status == 1) {
			result.setResultInfo("文章发表成功");
		} else {
			result.setResultInfo("已存为草稿");
		}
		int article_id = articleService.saveArticle(id, article, status);
		if (tag != null && status == 1) {
			tagService.saveTagArticle(article_id, tag);
		}
		result.getResultParm().put("article_id", article_id);
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}

	/**
	 * 上传图片.
	 */
	@RequestMapping(value = "/uploadimg", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public void uploadimg(
			@RequestParam(value = "editormd-image-file", required = false) MultipartFile attach,
			HttpServletRequest request, HttpServletResponse response) {
		String path = FileUploadUtil.NewFileUpload(request, attach,
				"articleimg");
		logger.info("上传图片访问地址：" + path);
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out;
		String s = "{\"success\": 1, \"message\":\"上传成功\",\"url\":\"../.."
				+ path + "\"}";
		try {
			out = response.getWriter();
			out.print(s);
			out.flush();
		} catch (IOException e) {
			try {
				response.getWriter().write("{\"success\":0}");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		// if (path != null) {
		// result.getResultParm().put("success", 0);
		// result.getResultParm().put("message", "上传失败");
		// result.setServiceResult(false);
		// }
		// result.getResultParm().put("success", 1);
		// result.getResultParm().put("message", "上传成功");
		// result.getResultParm().put("path", path);
		// result.setServiceResult(true);
		// return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}

	/**
	 * 查找单个文章
	 * 
	 * @param pageInfo
	 * @param status
	 * @return
	 */
	@RequestMapping(value = "/getOneArticle", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> getOneArticle(Integer article_id,
			Integer userdetail_id) {
		result = new ResultMessage();
		result.setServiceResult(true);
		Article article = articleService.findOneArticle(article_id);
		boolean collect_flag, follow_flag;
		if (article == null) {
			result.setServiceResult(false);
			result.setResultInfo("文章不存在");
		} else {
			// article.setContent_md(null);
			// 获取作者id
			
				UserDetail ud = userDetailService.getUserInfo(article
						.getUserDetail_id());
				
				if (userdetail_id==null||ud.getId() != userdetail_id) {
					article.setReading(article.getReading() + 1);
					articleService.updateArticle(article);
					article = articleService.findOneArticle(article_id);
				}
			if(userdetail_id!=null){
				// 获取收藏和关注状态
				collect_flag = articleService.getCollection(article_id,
						userdetail_id);
				follow_flag = articleService.getFollow(ud.getId(), userdetail_id);
				result.getResultParm().put("follow", follow_flag);
				result.getResultParm().put("collect", collect_flag);
			}
			List<Tag> tag_list = tagService.findTagByArticle(article.getId());
			result.getResultParm().put("user", ud);
			result.getResultParm().put("article", article);
			result.getResultParm().put("tag", tag_list);
		}
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}

	/**
	 * 删除单个文章
	 * 
	 * @param pageInfo
	 * @param status
	 * @return
	 */
	@RequestMapping(value = "/deleteArticle", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> deleteArticle(Integer article_id) {
		result = new ResultMessage();
		result.setServiceResult(true);
		articleService.deleteArticle(article_id);
		result.setResultInfo("删除成功");
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}

	/**
	 * 更新文章
	 * 
	 * @param pageInfo
	 * @param status
	 * @return
	 */
	@RequestMapping(value = "/updateArticle", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> updateArticle(Integer userdetail_id,
			Article article, Integer status, String tag) {
		result = new ResultMessage();
		result.setServiceResult(true);
		// 更新article表
		Article article_1 = articleService.updateArticleInfo(userdetail_id,
				article, status);
		// 获取以前相关的标签
		List<Tag> tag_list = tagService.findTagByArticle(article_1.getId());
		// 更新标签的阅读数 -1
		articleService.updateTagArticle(tag_list);
		// 删除相关的关联
		tagService.deleteByArticle(article_1.getId());
		// 重新关联标签
		tagService.saveTagArticle(article_1.getId(), tag);
		result.setResultInfo("更新文章成功");
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}
	/**
	 * 分页查询所有博文-按reading排序
	 * @param rank
	 * @param field
	 * @param pageInfo
	 * @return
	 */
	@RequestMapping(value = "/getArticleByRead", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> getArticleByRead(PageInfo pageInfo,
			Integer status) {
		result = new ResultMessage();
		result.setServiceResult(true);
		List<Article> article_list = articleService.getArticleByRead(pageInfo,
				status);
		if (article_list.size() <= 0) {
			result.setServiceResult(false);
			result.setResultInfo("没有更多了");
		}
		List<UserArticle> list = getUserArticle(article_list);
		result.getResultParm().put("article_user", list);
		result.getResultParm().put("total_count", pageInfo.getTotalCount());
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}
	/**
	 * 分页查询所有博文-按collecting排序
	 * @param rank
	 * @param field
	 * @param pageInfo
	 * @return
	 */
	@RequestMapping(value = "/getArticleByCollect", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> getArticleByCollect(PageInfo pageInfo,
			Integer status) {
		result = new ResultMessage();
		result.setServiceResult(true);
		List<Article> article_list = articleService.getArticleByCollect(pageInfo,
				status);
		if (article_list.size() <= 0) {
			result.setServiceResult(false);
			result.setResultInfo("没有更多了");
		}
		List<UserArticle> list = getUserArticle(article_list);
		result.getResultParm().put("article_user", list);
		result.getResultParm().put("total_count", pageInfo.getTotalCount());
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}
	/**
	 * 分页查询所有博文-按reward排序
	 * @param rank
	 * @param field
	 * @param pageInfo
	 * @return
	 */
	@RequestMapping(value = "/getArticleByReward", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> getArticleByReward(PageInfo pageInfo,
			Integer status) {
		result = new ResultMessage();
		result.setServiceResult(true);
		List<Article> article_list = articleService.getArticleByReward(pageInfo,
				status);
		if (article_list.size() <= 0) {
			result.setServiceResult(false);
			result.setResultInfo("没有更多了");
		}
		List<UserArticle> list = getUserArticle(article_list);
		result.getResultParm().put("article_user", list);
		result.getResultParm().put("total_count", pageInfo.getTotalCount());
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}
	/**
	 * 根据标题搜索
	 * @param pageInfo
	 * @param search
	 * @return
	 */
	@RequestMapping(value = "/searchArticle", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> searchArticle(PageInfo pageInfo,
			String search) {
		result = new ResultMessage();
		result.setServiceResult(true);
		List<Article> article_list = articleService.searchArticle(pageInfo,
				search);
		if (article_list.size() <= 0) {
			result.setServiceResult(false);
			result.setResultInfo("没有更多了");
		}
		List<UserArticle> list = getUserArticle(article_list);
		result.getResultParm().put("article_user", list);
		result.getResultParm().put("total_count", pageInfo.getTotalCount());
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}
	
	
	private List<UserArticle> getUserArticle(List<Article> article_list) {
		List<UserArticle> list = new ArrayList<UserArticle>();
		UserArticle userarticle = null;
		UserDetail ud = null;
		for (Article article : article_list) {
			ud = userDetailService.getUserInfo(article.getUserDetail_id());
			userarticle = new UserArticle(article, ud, tagService.findTagByArticle(article.getId()));
			list.add(userarticle);
		}
		return list;
	}
	
}
